package com.minelx.woods.server.dao;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.UpdateOptions;
import org.bson.Document;

import java.util.List;

import static java.util.Collections.emptyList;

public class ReviewerMapping {
	private final MongoCollection<Document> reviewerMappingsCollection;

	private final String userName;

	public ReviewerMapping(MongoCollection<Document> reviewerMappingsCollection, String userName) {
		this.reviewerMappingsCollection = reviewerMappingsCollection;
		this.userName = userName;
	}

	public void add(String reviewer) {
		reviewerMappingsCollection.updateOne(
				self(),
				new Document("$addToSet", new Document("reviewers", reviewer)),
				new UpdateOptions().upsert(true));
	}

	public void clear() {
		reviewerMappingsCollection.updateOne(
				self(),
				new Document("$set", new Document("reviewers", emptyList())),
				new UpdateOptions().upsert(true));
	}

	public List<String> reviewers() {
		Document self = reviewerMappingsCollection.find(self()).first();
		if (self == null) {
			return emptyList();
		}
		//noinspection unchecked
		return ((List<String>) self.get("reviewers", List.class));
	}

	private Document self() {
		return new Document("userName", userName);
	}
}
